﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using TwitterBootstrapMVC.Infrastructure;

namespace Web.UI.AdminLTE.Controls.Tab
{
    public class TabBuilder<TModel> : BuilderBase<TModel, TabControl>
    {
        private readonly Queue<string> _tabIds;
        private int _activeTabIndex;
        private bool _isFirstTab = true;
        private bool _isHeaderClosed;
        private int _panelIndex;
        private int _tabIndex;

        internal TabBuilder(HtmlHelper<TModel> htmlHelper, TabControl tabControl)
            : base(htmlHelper, tabControl, false)
        {
            _tabIndex = 1;
            _activeTabIndex = element.ActiveTabIndex;
            _tabIds = new Queue<string>();
            var text = element.InternalJustified ? " nav-justified" : "";
            var ulClasses = tabControl.HeaderClasses.Count > 0 ? string.Format(" {0}", string.Join(" ", tabControl.HeaderClasses)) : string.Empty;
            textWriter.Write("<ul class=\"nav nav-tabs{0}{1}\">", text, ulClasses);
        }

        public TabHeader Tab(string label, string tabId = null)
        {
            if (string.IsNullOrWhiteSpace(label))
            {
                throw new ArgumentNullException("label");
            }
            tabId = (tabId ?? (element.Id + "-" + _tabIndex));
            _tabIds.Enqueue(tabId);
            TabHeader result;
            if (_isFirstTab)
            {
                if (_activeTabIndex == 0)
                {
                    _activeTabIndex = 1;
                }
                result = new TabHeader(label, tabId, _tabIndex == _activeTabIndex);
                _isFirstTab = false;
            }
            else
            {
                result = new TabHeader(label, tabId, _tabIndex == _activeTabIndex);
            }
            _tabIndex++;
            return result;
        }

        public TabExtend TabExtend()
        {
            return new TabExtend(textWriter);
        }

        public TabPanel BeginPanel()
        {
            _panelIndex++;
            if (!_isHeaderClosed)
            {
                textWriter.Write("</ul>");
                _isHeaderClosed = true;
            }
            var id = _tabIds.Dequeue();
            if (_panelIndex == 1)
            {
                textWriter.Write("<div class=\"tab-content\">");
                _isFirstTab = false;
                return new TabPanel(textWriter, "div", id, _panelIndex == _activeTabIndex);
            }
            return new TabPanel(textWriter, "div", id, _panelIndex == _activeTabIndex);
        }

        internal HtmlHelper<TModel> GetHtmlHelper()
        {
            return htmlHelper;
        }

        public override void Dispose()
        {
            textWriter.Write("</div>");
            base.Dispose();
        }
    }
}